<?php
namespace app\common\util;
use app\common\util\JwtUtil;
use app\common\CommonConstant;
/**
 * 权限认证
 * @author xiegaolei
 *
 */
class AuthUtil
{
	/**
	 * 验证 接口调用权限
	 * @param boolean $isCheckLogin false or true
	 */
	public static function checkApiAuth() {
		
		$result1 = self::checkSign();
		$result2 = self::checkIdentity();
		
		if ($result1['status'] && $result2['status']){
			return msg_return( 1 ,$result2['msg']);
		}
		
		
	}
	
	/**
	 * 签名验证
	 */
	public static function checkSign() {
	 
		// 接口签名认证
		if ( config( "system.app_sign_auth_on" ) === true) {
			  
			$signature = input( "signature" ); // app端生成的签名
			$param = input ( "param." );
			unset($param['signature']);
			if ( empty($signature) || empty($param)) {
				my_exception(null, CommonConstant::e_api_sign_miss);
			}
				
			//数组排序
			ksort($param);
			$str = to_url_params($param);
			$signature1 = md5 ( sha1 ( $str ) . config( "system.app_sign_key" ) );
			  
			if ($signature != $signature1) {
				my_exception(null, CommonConstant::e_api_sign_wrong);
			}
			 
		}
		
		return msg_return(1,'ok');
		
	}
	
	/**
	 * 验证用户身份
	 * @param boolean $isCheckLogin false or true
	 */	
	public static function checkIdentity() {
		 
		// JWT访问令牌认证，令牌内容获取
		$userAccessToken = input ( 'userAccessToken' );
		$payload = JwtUtil::decode ( $userAccessToken );
		if ($payload === false || empty($payload->uid)) {
			my_exception(null, CommonConstant::e_api_access_token_miss);
		}
 
		// 实时用户数据认证：状态
		$user = db( 'user' )->getById ( $payload->uid );
		if ($user ['isEnabled'] != CommonConstant::db_true) {
			my_exception(null, CommonConstant::e_user_disabled);
		}
		
		return msg_return(1,$user);
	}
	
	
	
	
	
	
	
	
}
